<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTool>
        <!-- 利用具名插槽将内容传递给子组件 -->
        <!--vue2.6 之后写法v-slot:插槽名  -->
        <!-- vue2.6之前写法 slot:"插槽名" -->
        <template v-slot:before>
          <span>共{{ page.total }}条数据</span>
        </template>
        <template #after>
          <el-button
            type="danger"
            size="small"
            @click="onExport"
          >Excel导出</el-button>
          <!--导入部分是一个单独的组件 故要设置点击路由跳转到对应的页面 因此要提前设置好组件和路由 -->
          <el-button
            type="success"
            size="small"
            @click="$router.push('/import')"
          >Excel导入</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showAddDailog = true"
          >新增员工</el-button>
        </template>
      </PageTool>
      <el-card>
        <!--stripe 隔行变色(斑马纹)  sortable自动排序 -->
        <el-table :data="list" border stripe>
          <!-- el-table-column[label="" :sortable="true" prop=""]*10 -->
          <el-table-column
            width="50"
            label="序号"
            :sortable="true"
            type="index"
          ></el-table-column>
          <el-table-column
            label="姓名"
            :sortable="true"
            prop="username"
          ></el-table-column>
          <el-table-column
            label="头像"
            :sortable="true"
            prop="row.staffPhoto"
          ><template v-slot="{ row }">
            <!-- 这里是使用自定义指令的写法 -->
            <!-- <img v-imgerror="require('@/assets/common/head.jpg')" :src="row.staffPhoto" style="width:100px;height:100px;border-radius:50%"> -->
            <!-- 下面的写法是element提供的关于图片的 使用插槽-->
            <el-image
              :src="row.staffPhoto"
              style="width: 100px; height: 100px; border-radius: 50%"
              @click="onShowQrCodeDialog(row.staffPhoto)"
            >
              <img
                slot="error"
                src="@/assets/common/head.jpg"
                @click="
                  onShowQrCodeDialog(require('@/assets/common/head.jpg'))
                "
              /> </el-image></template>
          </el-table-column>
          <el-table-column
            label="手机号"
            :sortable="true"
            prop="mobile"
          ></el-table-column>
          <el-table-column
            label="工号"
            :sortable="true"
            prop="workNumber"
          ></el-table-column>
          <el-table-column
            label="聘用形式"
            :sortable="true"
            prop="formOfEmployment"
          >
            <template v-slot="{ row }">
              {{ row.formOfEmployment | formaHireType }}
            </template>
          </el-table-column>
          <el-table-column
            label="部门"
            :sortable="true"
            prop="departmentName"
          ></el-table-column>
          <el-table-column label="入职部门" :sortable="true" prop="timeOfEntry">
            <!-- 利用过滤器处理时间-->
            <template v-slot="{ row }">{{
              row.timeOfEntry | formadate
            }}</template>
          </el-table-column>
          <el-table-column label="状态" :sortable="true" prop="enableState">
            <template v-slot="{ row }">
              <el-switch
                v-model="row.enableState"
                disabled
                :active-value="1"
                active-color="green"
                :inactive-value="0"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            :sortable="true"
            fixed="right"
            width="280"
          >
            <template v-slot="{ row }">
              <el-button
                type="text"
                @click="$router.push('/emplyees/detail/' + row.id)"
              >查看</el-button>
              <el-button type="text">转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <!-- 点击打开对话框 -->
              <el-button
                type="text"
                @click="onShowAsignRoleDialog(row.id)"
              >角色</el-button>
              <el-button type="text" @click="onDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end">
          <el-pagination
            layout="total, prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            @current-change="onPageChange"
          ></el-pagination>
        </el-row>
      </el-card>
      <el-dialog title="显示二维码" :visible.sync="showQrDialog">
        <qrcode-vue :value="staffPhotoUrl" :size="size"></qrcode-vue>
      </el-dialog>
      <el-dialog
        :visible="showAddDailog"
        v-bind="$attrs"
        title="新增员工"
        v-on="$listeners"
        @open="onOpen"
        @close="close"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          size="medium"
          label-width="100px"
        >
          <el-form-item label="姓名" prop="username">
            <el-input
              v-model="form.username"
              placeholder="请输入姓名"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="form.mobile"
              placeholder="请输入手机号"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
          <el-form-item label="入职时间" prop="timeOfEntry">
            <el-date-picker
              v-model="form.timeOfEntry"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :style="{ width: '100%' }"
              placeholder="请选择入职时间"
              clearable
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="聘用形式" prop="formOfEmployment">
            <el-select
              v-model="form.formOfEmployment"
              placeholder="请选择聘用形式"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in formOfEmploymentOptions"
                :key="index"
                :label="item.value"
                :value="item.id"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工号" prop="workNumber">
            <el-input
              v-model="form.workNumber"
              placeholder="请输入工号"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
          <el-form-item label="部门" prop="departmentName">
            <el-input
              v-model="form.departmentName"
              placeholder="请输入部门"
              clearable
              :style="{ width: '100%' }"
              @focus="getDeptsList"
            >
            </el-input>
            <el-tree
              v-if="showTree"
              :data="depts"
              :props="{ label: 'name' }"
              @node-click="handleNodeClick"
            ></el-tree>
          </el-form-item>
          <el-form-item
            label="
              转正时间"
            prop="correctionTime"
          >
            <el-date-picker
              v-model="form.correctionTime"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :style="{ width: '100%' }"
              placeholder="请选择转正时间"
              clearable
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <el-row slot="footer" type="flex" justify="center">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="handelConfirm">确定</el-button>
        </el-row>
      </el-dialog>
      <!-- 通过eldi代码片段写下面的 -->
      <!-- 头:分配角色部分 -->
      <el-dialog
        title="分配角色"
        :visible.sync="showAsignRoleDialog"
        width="50%"
        @close="showAsignRoleDialog = false"
      >
        <!-- 头: 角色分配弹出来的对话框里面的多选框 用的是element里面的多选框 -->
        <el-checkbox-group v-model="roleIds">
          <el-checkbox
            v-for="(item,index) in roleList"
            :key="index"
            :label="item.id"
          >{{ item.name }}</el-checkbox>
        </el-checkbox-group>
        <!--尾:-->
        <el-row slot="footer" type="flex" justify="center">
          <el-button @click="showAsignRoleDialog = false">取消</el-button>
          <el-button type="primary" @click="asignRole">确定</el-button>
        </el-row>
      </el-dialog>
      <!-- 尾:分配角色部分 -->
    </div>
  </div>
</template>

<script>
import { getList } from '@/api/departments.js'
import { addEmployee, getEmployees, delEmployee, assignRoles } from '@/api/employees'
// 导入二维码
import QrcodeVue from 'qrcode.vue'
// 导入枚举的文件
import employeesEnum from '@/api/constant/employees'
import { translateListToTree } from '@/utils'
// 下载依赖  引入lodash中的pick方法
import { pick } from 'lodash'
// 引入过滤器
import { formadate, formaHireType } from '@/filters/index.js'
import { getRolesList } from '@/api/setting'
import { getEmplyeeBaseInfo } from '@/api/user'
export default {
  name: 'Employees',
  components: { QrcodeVue },
  props: {
  },
  data() {
    return {
      userId: undefined, // 用于存放当前选中的id
      roleIds: [], // 用于保存角色分配中已经被选中的角色
      roleList: [], // 定义角色分配中的多选框数据
      form: {
        username: undefined,
        mobile: undefined,
        timeOfEntry: null,
        formOfEmployment: undefined,
        workNumber: undefined,
        departmentName: undefined,
        correctionTime: null
      },
      showTree: false, // 部门下拉的树形结构的初始状态
      rules: {
        username: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        }],
        mobile: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        }],
        timeOfEntry: [{
          required: true,
          message: '请选择入职时间',
          trigger: 'change'
        }],
        formOfEmployment: [{
          required: true,
          message: '请选择聘用形式',
          trigger: 'change'
        }],
        workNumber: [{
          required: true,
          message: '请输入工号',
          trigger: 'blur'
        }],
        // 更改验证 将失去焦点blur改成change
        departmentName: [{
          required: true,
          message: '请输入部门',
          trigger: 'change'
        }],
        correctionTime: []
      },
      formOfEmploymentOptions: employeesEnum.hireType,
      // 新增员工的对话框的显示初始状态
      showAddDailog: false,
      showAsignRoleDialog: false, // 定义控制对话框的初始状态
      list: [],
      // 点击图片显示二维码的初始状态
      showQrDialog: false,
      page: {
        page: 1,
        size: 8,
        total: 0
      },
      // 图片的地址初始值
      staffPhotoUrl: undefined,
      size: 300,
      depts: []
    }
  },
  created() {
    this.getList()
  },
  mounted() { },
  methods: {
    // 导出事件
    onExport() {
      // 在这里导入是懒加载按需导入
      import('@/vendor/Export2Excel').then(async excel => {
        const headers = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const { rows } = await getEmployees({
          page: 1,
          size: this.page.total
        })
        const values = Object.values(headers) // 1. 获取到headers里面对应的值
        // 2. 遍历rows 将符合headers里面的值的对象找出来
        const data = rows.map(t => {
          const item = pick(t, values)
          // 通过过滤器里面的方法
          item.timeOfEntry = formadate(item.timeOfEntry)
          item.correctionTime = formadate(item.correctionTime)
          item.formOfEmployment = formaHireType(item.formOfEmployment)
          // 将对象转换成数组的形式
          return Object.values(item)
        })
        console.log(rows)
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data: data, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    onDel(id) {
      // 确认删除的代码片段elmecon
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        await delEmployee(id)
        this.message.success('删除成功啦~')
        this.getList()
      })
    },
    handleNodeClick(data) {
      // 1. 选中后关闭树形机构
      this.showTree = false
      // 2. 将部门名称赋值给表单的部门名称
      this.form.departmentName = data.name
    },
    async getDeptsList() {
      // 点击部门的时候 展开树形结构
      this.showTree = true
      this.depts = translateListToTree((await getList()).depts, '')
    },
    async getList() {
      const { total, rows } = await getEmployees(this.page)
      this.page.total = total
      this.list = rows
    },
    // 页码改变的事件
    onPageChange(value) {
      // 1. 将选中的页码赋值给page
      this.page.page = value
      // 2. 重新刷新
      this.getList()
    },
    // 点击图片的事件
    onShowQrCodeDialog(url) {
      // 将row.staffPhoto赋值给二维码的地址
      this.staffPhotoUrl = url
      // 打开对话框
      this.showQrDialog = true
    },
    onOpen() { },
    close() {
      this.$refs['formRef'].resetFields()
      this.showAddDailog = false
    },
    handelConfirm() {
      this.$refs['formRef'].validate(async valid => {
        if (!valid) return
        // 1.发请求 新增员工 将form的值发过去
        await addEmployee(this.form)
        // 2.提示成功的消息
        this.message.success('操作成功')
        // 3. 刷新页面
        this.getList()
        // 4. 关闭对话框
        this.close()
      })
    },
    // 点击角色弹出对话框事件
    async onShowAsignRoleDialog(id) {
      // 打开对话框 进行数据回显  获取到所有的角色
      const { roleIds } = await getEmplyeeBaseInfo(id)
      this.roleIds = roleIds
      const { rows } = await getRolesList({
        page: 1,
        pagesize: 50
      })
      this.roleList = rows
      this.showAsignRoleDialog = true
      this.userId = id
    },
    // 确认角色分配
    async asignRole() {
      // 1. 调用接口
      await assignRoles({
        id: this.userId, // 因为这里要传用户的id,所以必须要使用到上一个方法的id.因此在data里面去定义一个用户的id.然后在上一个方法中将用户的id存入进去
        roleIds: this.roleIds
      })
      // 2. 关闭对话框
      this.showAsignRoleDialog = false
      this.$message.success('操作成功')
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
